package cn.okcode.api.framework.result;


import cn.okcode.api.framework.Callee;
import cn.okcode.api.framework.TraceLogger;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

import java.util.Map;

/**
 * 状态结果处理器
 * 返回成功或者失败状态标识，以及接口执行结果对象
 *
 * @author pyk13
 */
public class StatusResultHandler implements ResultHandler {
    @Override
    public String ok(Object res) {
        //注意：这里不能加上SerializerFeature.DisableCircularReferenceDetect参数，否则对象出现循环引用的时候fastjson不会自动停止遍历
        return JSON.toJSONString(ResultUtil.ok(res), SerializerFeature.WriteMapNullValue);
    }

    @Override
    public String err(Callee callee, String msg, Throwable e) {
        String message = TraceLogger.getMessage();
        Map<String, Object> result = ResultUtil.err(msg, e);
        if (!message.isEmpty()) {
            TraceLogger.removeMessage();
            result.put("traceMessage", message);
        }
        return JSON.toJSONString(result);
    }
}
